package com.efast.cafe.framework.freemarker;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.efast.cafe.util.ConfigUtil;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;
import freemarker.core.ParseException;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;
@Service
public class PdfGenerateService {
	
	@Autowired
    private FreeMarkerConfigurer configurer;
	
	 public ITextRenderer getRender() throws DocumentException, IOException {
		 
	        ITextRenderer render = new ITextRenderer();
	 
	        String path = getPath();
	        //添加字体，以支持中文
	        render.getFontResolver().addFont(path + "template/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
	        render.getFontResolver().addFont(path + "template/fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
	 
	        return render;
	    }
	 
	 
	//获取要写入PDF的内容
	    public  String getPdfContent(String ftlName, Object o) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException, TemplateException {
	        return useTemplate(ftlName, o);
	    }
	 
	    //使用freemarker得到html内容
	    public  String useTemplate(String ftlName, Object o) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException, TemplateException {
	        try{
	        	configurer.getConfiguration().setClassLoaderForTemplateLoading(Thread.currentThread().getContextClassLoader(), "template");
	        }catch(Exception e){
	        	configurer.getConfiguration().setClassLoaderForTemplateLoading(ClassLoader.getSystemClassLoader(), "template");
	        }
	    	
			configurer.getConfiguration().setDefaultEncoding("UTF-8");
			Template template = configurer.getConfiguration().getTemplate(ftlName);
			Map<String, Object> model = new HashMap<>();
			model.put("params", o);
			return FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
			
	    }
	 
	    /**
	     * 获取类路径
	     * @return
	     */
	    public  String getPath(){
	    	try{
	    		return Thread.currentThread().getContextClassLoader().getResource("/").toString();
	    	}catch(Exception e){
	    		return PdfGenerateService.class.getResource("/").getPath().substring(1);
	    	}
	    	
	    }
	    
	   
	    
	    /**
	     * 生成PDF到文件
	     * @param ftlPath 模板文件路径（不含文件名）
	     * @param ftlName 模板文件吗（不含路径）
	     * @param imageDiskPath 图片的磁盘路径
	     * @param data 数据
	     * @param outputFile 目标文件（全路径名称）
	     * @throws Exception
	     */
	    public  void generateToFile(String ftlName,Object data,String outputFile) throws Exception {
	        String html=getPdfContent(ftlName, data);
	        OutputStream out = null;
	        try{
	        	ITextRenderer render = null;
		        out = new FileOutputStream(outputFile);
		        render = getRender();
		        render.setDocumentFromString(html);
		        render.getSharedContext().setBaseURL("file://"+getPath()+"template/images/");
		        render.layout();
		        render.createPDF(out);
		        out.flush();
		        render = null;
	        }catch(Exception e){
	        	e.printStackTrace();
	        }finally {
	        	out.close();
			}
	        
	    }
	    
	 
	    
	    
	    /**
	     * 生成PDF到输出流中（ServletOutputStream用于下载PDF）
	     * @param ftlPath ftl模板文件的路径（不含文件名）
	     * @param ftlName ftl模板文件的名称（不含路径）
	     * @param imageDiskPath 如果PDF中要求图片，那么需要传入图片所在位置的磁盘路径
	     * @param data 输入到FTL中的数据
	     * @param response HttpServletResponse
	     * @return
	     * @throws TemplateNotFoundException
	     * @throws MalformedTemplateNameException
	     * @throws ParseException
	     * @throws IOException
	     * @throws TemplateException
	     * @throws DocumentException
	     */
	    public  OutputStream generateToServletOutputStream(String ftlName,Object data,HttpServletResponse response) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException, TemplateException, DocumentException{
	        String html=getPdfContent(ftlName, data);
	        OutputStream out = null;
	        ITextRenderer render = null;
	        out = response.getOutputStream();
	        render = getRender();
	        render.setDocumentFromString(html);
	        render.getSharedContext().setBaseURL("file://"+getPath()+"template/images/");
	        render.layout();
	        render.createPDF(out);
	        render.finishPDF();
	        render = null;
	        return out;
	    }
	    
}
